package org.utem.datacollector;

import java.util.List;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.widget.Toast;

public class WifiScanSensor extends SensorCollector{
	private WifiManager wm;
	private Context context;
	private List<ScanResult> scanResults;
	private BroadcastReceiver wfbr = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String intentAction = intent.getAction();
            if (intentAction.equalsIgnoreCase(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
                scanResults = wm.getScanResults();
                wm.startScan();
            }
        }
    };

    public WifiScanSensor(Context context) {
        this.context = context;
        wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (!wm.isWifiEnabled()){
            if (wm.getWifiState() != WifiManager.WIFI_STATE_ENABLING){
                wm.setWifiEnabled(true);
            }
        }
    }

	@Override
	public void iniciarSensor() {
		if (wm != null){
			IntentFilter intentFilter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
			context.registerReceiver(this.wfbr, intentFilter);
			wm.startScan();
		} else {
			Toast.makeText(context, "No existe tarjeta Wi-Fi", Toast.LENGTH_LONG).show();
		}
	}

	@Override
	public void detenerSensor() {
		if (wm != null){
			if (wm.isWifiEnabled()){
				wm.setWifiEnabled(false);
			}
	    	context.unregisterReceiver(this.wfbr);
		}
	}
	
	public List<ScanResult> getScanResults() {
		return scanResults;
	}
}
